feat(run): npm tool window with the project's package.json scripts (#5217)

A new npm tool window on the right lists the scripts of every package.json in the project (root, workspace members, detected module roots and any other package.json the index knows outside node_modules), grouped by package. Double-click runs a script; the context menu offers Run / Debug through the same path as the package.json gutter, reusing a matching run configuration or creating a temporary one. The window appears only while the project has scripts and refreshes when a package.json changes or indexing finishes. The editor context menu on a package.json script line also offers Run / Debug for that script.

Co-authored-by: lifeir <132877455+lifeir@users.noreply.github.com>
This commit is contained in:
lifeir
2026-11-22 21:10:59 +08:00
committed by GitHub
parent 08d719e03d
commit f2b06bc376
9 changed files with 359 additions and 0 deletions
+44
View File
@@ -0,0 +1,44 @@
/** 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();
});
+77
View File
@@ -0,0 +1,77 @@
/** 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<MenuItem[]> {
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<ReadonlySet<string>>(() => 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 (
<span className={styles.scriptsRow} title={n.label}>
<Icon name="file-npm" size={16} />
<span className={state.selected ? styles.scriptsStrong : undefined}>{n.label}</span>
<span className={styles.scriptsMeta}>{n.scripts.length}</span>
</span>
);
}
return (
<span className={styles.scriptsRow} title={n.name}>
<Icon name="runnable-mark" size={14} />
<span>{n.name}</span>
</span>
);
};
return (
<Tree<NpmNode>
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}
/>
);
}
+17
View File
@@ -6,6 +6,23 @@
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;
+12
View File
@@ -82,6 +82,18 @@ describe("run context menu group", () => {
expect(items[0]).toMatchObject({ arg: { path: `${SCRATCHES}/hi.ts`, line: 0, dir: false } });
});
it("editor: offers Run / Debug '<script>' on a package.json script line", () => {
const text = '{\n "scripts": {\n "dev": "vite",\n "build": "vite build"\n }\n}\n';
// Line 2 (0-based) is the "dev" entry.
const items = contextMenuItems("editor", { paths: [`${ROOT}/package.json`], text, line: 2 });
expect(items.map((i) => ("label" in i ? i.label : i.kind))).toEqual(["Run 'dev'", "Debug 'dev'"]);
expect(items[0]).toMatchObject({ icon: "run" });
expect(items[1]).toMatchObject({ icon: "debug" });
// Other lines get the usual menu.
const other = contextMenuItems("editor", { paths: [`${ROOT}/package.json`], text, line: 0 });
expect(other.map((i) => ("label" in i ? i.label : i.kind))).not.toContain("Run 'dev'");
});
it("editor: the element at the caret names the entries", () => {
const text = "describe('math', () => {\n it('adds', () => {\n expect(1).toBe(1);\n });\n});\n";
const at = (line: number) => contextMenuItems("editor", { paths: [`${ROOT}/src/m.test.ts`], text, line })[0];
+19
View File
@@ -34,6 +34,7 @@ import {
} from "./producers";
import { runWithExecutor } from "./executors";
import { jdwpLaunch } from "./javaDebug";
import { scriptEntries, scriptMenuItems, type ScriptEntry } from "./npmGutter";
import { goModulePath, loadGoModules } from "./goModules";
import { isPythonPackage, loadPythonPackages } from "./pythonPackages";
import { remoteDebugBlocked } from "./remote";
@@ -392,6 +393,19 @@ export async function prepareMenu(_menu: ContextMenuId, ctx: MenuGroupContext):
peeked.set(path, { at: Date.now(), text: text.slice(0, CONTENT_LIMIT) });
}
/** Run / Debug for a `package.json` script line, through `scriptMenuItems`. */
function npmScriptItems(entry: ScriptEntry, path: string, content: string): MenuItem[] {
const run = async (debug: boolean) => {
const items = await scriptMenuItems(entry, path, content);
const item = items[debug ? 1 : 0];
if (item && "run" in item) item.run?.();
};
return [
{ label: tx`Run '${entry.name}'`, icon: "run", run: () => void run(false) },
{ label: tx`Debug '${entry.name}'`, icon: "debug", run: () => void run(true) },
];
}
/** The run group of a context menu: Run / Debug '<name>', Modify Run Configuration…. */
export function contextMenuItems(menu: ContextMenuId, ctx: MenuGroupContext): MenuItem[] {
if (ctx.paths.length !== 1) return [];
@@ -402,6 +416,11 @@ export function contextMenuItems(menu: ContextMenuId, ctx: MenuGroupContext): Me
const dir = !!ctx.dirs?.[0];
const content = ctx.text ?? peekContent(path);
const line = menu === "editor" ? ctx.line : undefined;
// A `package.json` script line runs that script.
if (!dir && /(^|\/)package\.json$/.test(path) && content !== undefined && line !== undefined) {
const entry = scriptEntries(content.slice(0, CONTENT_LIMIT)).find((e) => e.line === line);
if (entry) return npmScriptItems(entry, path, content);
}
const input: ContextInput = {
...projectContext(),
root,
+2
View File
@@ -70,6 +70,7 @@ 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";
@@ -435,6 +436,7 @@ 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(),
+186
View File
@@ -0,0 +1,186 @@
/**
* 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<NpmScriptsState>(() => ({ loaded: false, packages: [] }));
const safeJson = (text: string): Record<string, unknown> | null => {
try {
return JSON.parse(text) as Record<string, unknown>;
} 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<string, unknown>, root: string): Promise<string[]> {
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<void> {
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` ("<dir>/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<void> {
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);
};
}
+1
View File
@@ -1484,6 +1484,7 @@
"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",
"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.",
"This is not a global npm install OpenIDEA can update. Use its original installer.": "This is not a global npm install OpenIDEA can update. Use its original installer.",
+1
View File
@@ -7912,6 +7912,7 @@
"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 全局安装。请使用原安装工具更新。",