diff --git a/e2e/npmScripts.spec.ts b/e2e/npmScripts.spec.ts deleted file mode 100644 index 8d92c90303..0000000000 --- a/e2e/npmScripts.spec.ts +++ /dev/null @@ -1,44 +0,0 @@ -/** The npm tool window lists package.json scripts without run configurations and runs them. */ -import type { Page } from "@playwright/test"; -import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; - -const PKG = JSON.stringify({ name: "acme-api", scripts: { dev: "vite", build: "vite build" } }); - -/** The root package.json has scripts; there are no run configurations. */ -async function stubNpm(page: Page) { - await stubDesktop(page); - await page.evaluate(async (pkg) => { - const h = window.__ipc.handlers; - h.fs_read_text = (args) => (String(args.path).endsWith("/package.json") ? pkg : ""); - h.run_configs = () => []; - h.run_start = (args) => { - const config = args.config as { id: string; name: string }; - return { id: 8, configId: config.id, name: config.name, pid: 4242, running: true, pty: false }; - }; - const npmModule = "/src/features/run/npmScripts.ts"; - const { loadNpmScripts } = await import(/* @vite-ignore */ npmModule); - await loadNpmScripts(); - }, PKG); -} - -test("lists scripts without run configurations and runs one on double-click", async ({ workbench: page }) => { - await stubNpm(page); - await page.getByRole("button", { name: "npm", exact: true }).click(); - const tree = page.getByRole("tree", { name: "npm scripts" }); - await expect(tree).toBeVisible(); - await expect(tree.getByRole("treeitem", { name: /^acme-api/ })).toBeVisible(); - await expect(tree.getByRole("treeitem", { name: "dev" })).toBeVisible(); - await expect(tree.getByRole("treeitem", { name: "build" })).toBeVisible(); - await tree.getByRole("treeitem", { name: "dev" }).dblclick(); - const [started] = await ipcCalls(page, "run_start"); - expect(started).toMatchObject({ config: { args: ["run", "dev"], kind: "npm" } }); -}); - -test("offers Run / Debug in a script's context menu", async ({ workbench: page }) => { - await stubNpm(page); - await page.getByRole("button", { name: "npm", exact: true }).click(); - const tree = page.getByRole("tree", { name: "npm scripts" }); - await tree.getByRole("treeitem", { name: "build" }).click({ button: "right" }); - await expect(page.getByRole("menuitem", { name: /Run '.*run build'/ })).toBeVisible(); - await expect(page.getByRole("menuitem", { name: /Debug '.*run build'/ })).toBeVisible(); -}); diff --git a/src/features/run/NpmScriptsView.tsx b/src/features/run/NpmScriptsView.tsx deleted file mode 100644 index 6ac0d0dbb7..0000000000 --- a/src/features/run/NpmScriptsView.tsx +++ /dev/null @@ -1,77 +0,0 @@ -/** The npm tool window: the project's packages and their scripts; activating a script runs it. */ -import { useMemo, useState, type ReactNode } from "react"; -import { tx } from "@/platform/i18n"; -import { useProject } from "@/platform/project"; -import { Icon, Tree, showContextMenu, type MenuItem, type TreeRowState } from "@/ui"; -import { runScriptNode, useNpmScripts, type NpmNode } from "./npmScripts"; -import { scriptMenuItems } from "./npmGutter"; -import { call, commands } from "@/platform/ipc"; -import styles from "./Run.module.css"; - -function scriptMenuItemsFor(node: NpmNode): Promise { - if (node.kind !== "script") return Promise.resolve([]); - return call(commands.fsReadText(node.path)) - .catch(() => "") - .then((content) => scriptMenuItems({ name: node.name, line: 0 }, node.path, content ?? "")); -} - -export function NpmScriptsView() { - const packages = useNpmScripts((s) => s.packages); - const loaded = useNpmScripts((s) => s.loaded); - const hasProject = useProject((s) => !!s.project); - const [collapsed, setCollapsed] = useState>(() => new Set()); - - const roots = useMemo(() => packages, [packages]); - const expanded = useMemo( - () => new Set(roots.filter((n) => n.kind === "package" && !collapsed.has(n.key)).map((n) => n.key)), - [roots, collapsed], - ); - - if (!loaded || !hasProject || roots.length === 0) return null; - - const renderNode = (n: NpmNode, state: TreeRowState): ReactNode => { - if (n.kind === "package") { - return ( - - - {n.label} - {n.scripts.length} - - ); - } - return ( - - - {n.name} - - ); - }; - - return ( - - aria-label={tx`npm scripts`} - roots={roots} - getKey={(n) => n.key} - getLabel={(n) => (n.kind === "package" ? n.label : n.name)} - getChildren={(n) => (n.kind === "package" ? n.scripts : undefined)} - isExpandable={(n) => n.kind === "package"} - expanded={expanded} - onExpandedChange={(_next, node, isOpen) => - setCollapsed((prev) => { - const s = new Set(prev); - if (isOpen) s.delete(node.key); - else s.add(node.key); - return s; - }) - } - onActivate={(n) => { - if (n.kind === "script") void runScriptNode(n, false); - }} - onContextMenu={(n, _sel, e) => { - if (n?.kind !== "script") return; - void scriptMenuItemsFor(n).then((items) => showContextMenu({ clientX: e.clientX, clientY: e.clientY }, items)); - }} - renderNode={renderNode} - /> - ); -} diff --git a/src/features/run/Run.module.css b/src/features/run/Run.module.css index 9afb904ef8..d83150e7f9 100644 --- a/src/features/run/Run.module.css +++ b/src/features/run/Run.module.css @@ -6,23 +6,6 @@ min-width: 0; } -.scriptsRow { - display: flex; - align-items: center; - gap: var(--space-1); - min-width: 0; -} - -.scriptsStrong { - font-weight: 500; -} - -.scriptsMeta { - flex: none; - color: var(--fg-subtle); - font-size: var(--fs-small); -} - .tabs { min-width: 0; border: 0; diff --git a/src/features/run/index.ts b/src/features/run/index.ts index e4b2415c1d..f65fdb7413 100644 --- a/src/features/run/index.ts +++ b/src/features/run/index.ts @@ -72,7 +72,6 @@ import { junitType } from "./junitType"; import { listenForApplicationDeactivation, showApplicationUpdate, updatableSessions } from "./applicationUpdate"; import { hotReload, hotReloadSession, hotRestart } from "./flutterHotReload"; import { npmGutter } from "./npmGutter"; -import { startNpmScriptsWatch } from "./npmScripts"; import { launchSettingsGutter } from "./launchSettingsGutter"; import { runGutter } from "./runGutter"; import { markdownCommandGutter } from "./markdownCommands"; @@ -438,7 +437,6 @@ export function activate(): () => void { headerContent: lazyComponent(() => import("./RunView").then((m) => m.RunTabs)), useBadge: useRunningCount, }), - startNpmScriptsWatch(), registerTitleItem({ id: "run.widget", title: "Run Widget", align: "right", priority: 0, component: RunWidget }), registerRunAnythingProvider(runConfigsRunAnything), registerBuiltinTypes(), diff --git a/src/features/run/npmScripts.ts b/src/features/run/npmScripts.ts deleted file mode 100644 index 450a4d791d..0000000000 --- a/src/features/run/npmScripts.ts +++ /dev/null @@ -1,186 +0,0 @@ -/** - * The npm tool window's data: the project's `package.json` files (root, workspace members and - * detected module roots) read from disk, independent of run configuration detection. Running a - * script goes through `scriptMenuItems`, which reuses a matching configuration or makes a temporary one. - */ -import { create } from "zustand"; -import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc"; -import { useProject } from "@/platform/project"; -import { useProjectRoots } from "@/platform/projectRoots"; -import { lazyComponent } from "@/ui"; -import { registerToolWindow } from "@/workbench/contributions"; -import { objectEntries, scriptMenuItems, type ScriptEntry } from "./npmGutter"; - -/** A package (the directory of a `package.json`) or one of its scripts. */ -export type NpmNode = { kind: "package"; key: string; label: string; scripts: NpmScript[] } | NpmScript; - -export interface NpmScript { - kind: "script"; - key: string; - /** Directory relative to the project root ("" for the root package). */ - dir: string; - /** Absolute path of the `package.json`. */ - path: string; - name: string; -} - -interface NpmScriptsState { - loaded: boolean; - packages: NpmNode[]; -} - -export const useNpmScripts = create(() => ({ loaded: false, packages: [] })); - -const safeJson = (text: string): Record | null => { - try { - return JSON.parse(text) as Record; - } catch { - return null; - } -}; - -/** Member directories (relative to the root) of the root package's `workspaces`: plain paths and one `*` level. */ -async function workspaceDirs(pkg: Record, root: string): Promise { - const ws = pkg.workspaces; - const list = Array.isArray(ws) - ? (ws as unknown[]) - : Array.isArray((ws as { packages?: unknown[] })?.packages) - ? (ws as { packages: unknown[] }).packages - : []; - const out: string[] = []; - for (const pattern of list) { - if (typeof pattern !== "string" || !pattern || pattern.includes("..")) continue; - const star = pattern.indexOf("*"); - if (star < 0) { - out.push(pattern.replace(/\/+$/, "")); - continue; - } - const parent = pattern.slice(0, star).replace(/\/+$/, ""); - const suffix = pattern.slice(star + 1); - const entries = await call(commands.fsReadDir(parent ? `${root}/${parent}` : root)).catch(() => []); - for (const e of entries) { - const isDir = e.kind === "dir" || e.targetKind === "dir"; - if (!isDir || e.ignored || e.excluded || e.name === "node_modules") continue; - if (suffix && !e.name.endsWith(suffix)) continue; - out.push(parent ? `${parent}/${e.name}` : e.name); - } - } - return out; -} - -let loadGen = 0; - -/** Rescans the packages and their scripts. */ -export async function loadNpmScripts(): Promise { - const root = useProject.getState().project?.root ?? null; - const gen = ++loadGen; - if (!root || !isTauri()) { - useNpmScripts.setState({ loaded: true, packages: [] }); - return; - } - const rootName = useProject.getState().project?.name ?? root; - const dirs = new Set([""]); - const rootText = await call(commands.fsReadText(`${root}/package.json`)).catch(() => null); - const rootPkg = rootText !== null ? safeJson(rootText) : null; - if (rootPkg) for (const dir of await workspaceDirs(rootPkg, root)) dirs.add(dir); - // Detected roots cover a front end in a subdirectory. A node module's own directory only shows - // up in `detectedFrom` ("/package.json"). Roots outside the project (absolute) are skipped. - for (const r of useProjectRoots.getState().detected) { - const abs = r.path.startsWith(`${root}/`) ? r.path.slice(root.length + 1) : r.path; - const rel = /^[A-Za-z]:[\\/]|^\//.test(abs) ? null : abs; - if (rel === null) continue; - if (r.kind !== "excluded" && rel) dirs.add(rel); - if (r.detectedFrom) { - const moduleDir = r.detectedFrom.replace(/\/[^/]+$/, ""); - if (moduleDir && !/^[A-Za-z]:[\\/]|^\//.test(moduleDir)) dirs.add(moduleDir); - } - } - // Any other package.json the index knows, outside node_modules. - const indexed = await call(commands.findFilesNamed("package.json")).catch(() => []); - for (const file of indexed.slice(0, 500)) { - const path = String(file).replace(/\\/g, "/"); - if (!path.startsWith(`${root}/`) || path.includes("/node_modules/")) continue; - dirs.add(path.slice(root.length + 1).replace(/\/?package\.json$/, "")); - } - const packages: NpmNode[] = []; - await Promise.all( - [...dirs].map(async (dir) => { - const path = dir ? `${root}/${dir}/package.json` : `${root}/package.json`; - const text = await call(commands.fsReadText(path)).catch(() => null); - if (text === null) return; - const scripts: NpmScript[] = objectEntries(text, "scripts").map((e: ScriptEntry) => ({ - kind: "script" as const, - key: `npm:${dir ? `${dir}:` : ""}${e.name}`, - dir, - path, - name: e.name, - })); - if (scripts.length === 0) return; - scripts.sort((a, b) => a.name.localeCompare(b.name)); - packages.push({ kind: "package", key: `pkg:${dir}`, label: dir === "" ? rootName : dir, scripts }); - }), - ); - if (gen !== loadGen) return; - packages.sort((a, b) => - a.kind === "package" && b.kind === "package" - ? a.label === rootName - ? -1 - : b.label === rootName - ? 1 - : a.label.localeCompare(b.label) - : 0, - ); - useNpmScripts.setState({ loaded: true, packages }); -} - -/** Runs or debugs a script the way its gutter icon does. */ -export async function runScriptNode(node: NpmScript, debug: boolean): Promise { - const content = await call(commands.fsReadText(node.path)).catch(() => ""); - const entry: ScriptEntry = { name: node.name, line: 0 }; - const items = await scriptMenuItems(entry, node.path, content ?? ""); - const item = items[debug ? 1 : 0]; - if (item && "run" in item) item.run?.(); -} - -/** Keeps the scripts current and shows the npm tool window while the project has any. */ -export function startNpmScriptsWatch(): () => void { - let unregister: (() => void) | null = null; - let indexing = true; - const syncToolWindow = (has: boolean) => { - if (has && !unregister) - unregister = registerToolWindow({ - id: "npm-scripts", - title: "npm", - icon: "file-npm", - anchor: "right", - order: 13, - component: lazyComponent(() => import("./NpmScriptsView").then((m) => m.NpmScriptsView)), - }); - else if (!has && unregister) { - unregister(); - unregister = null; - } - }; - const disposers = [ - useNpmScripts.subscribe((s) => syncToolWindow(s.packages.length > 0)), - useProject.subscribe((s, prev) => { - if (s.project?.root !== prev.project?.root) void loadNpmScripts(); - }), - useProjectRoots.subscribe((s, prev) => { - if (s.detected !== prev.detected || s.root !== prev.root) void loadNpmScripts(); - }), - onIdeEvent("indexState", (e) => { - if (indexing && !e.indexing) void loadNpmScripts(); - indexing = e.indexing; - }), - onIdeEvent("fsChanged", (e) => { - const changed = [...e.created, ...e.modified, ...e.removed]; - if (changed.some((p) => /(^|\/)package\.json$/.test(p) && !p.includes("/node_modules/"))) void loadNpmScripts(); - }), - ]; - void loadNpmScripts(); - return () => { - disposers.forEach((d) => d()); - syncToolWindow(false); - }; -} diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 8c43d8407c..f6f169ac93 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1891,7 +1891,6 @@ "Updated to {0}. New sessions will use this version.": "Updated to {0}. New sessions will use this version.", "Installed: {0} · No newer npm release.": "Installed: {0} · No newer npm release.", "Installed: {0}. Use your installer to manage this release channel.": "Installed: {0}. Use your installer to manage this release channel.", - "npm scripts": "npm scripts", "database": "database", "npm could not complete the operation ({0}).": "npm could not complete the operation ({0}).", "An update for this agent is already running.": "An update for this agent is already running.", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 53727ccef0..604ac93dd7 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -8325,7 +8325,6 @@ "Updated to {0}. New sessions will use this version.": "已更新到 {0}。新会话将使用此版本。", "Installed: {0} · No newer npm release.": "已安装:{0} · 没有更新的 npm 版本。", "Installed: {0}. Use your installer to manage this release channel.": "已安装:{0}。请使用原安装工具管理此发布渠道。", - "npm scripts": "npm 脚本", "npm could not complete the operation ({0}).": "npm 无法完成操作({0})。", "An update for this agent is already running.": "此智能体已有更新正在进行。", "This is not a global npm install OpenIDEA can update. Use its original installer.": "这不是 OpenIDEA 能更新的 npm 全局安装。请使用原安装工具更新。",