import type { ExecFileOptions } from "node:child_process"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const { execute } = vi.hoisted(() => ({ execute: vi.fn() })); vi.mock("node:child_process", async () => { const actual = await vi.importActual( "node:child_process", ); const { promisify } = await import("node:util"); return { ...actual, execFile: Object.defineProperty(vi.fn(), promisify.custom, { value: execute, }), }; }); import { diagnosticHelp } from "../diagnostic-help.ts"; const source = "version --bogus"; const flagSpan = { start: 1008, end: 1015 }; let block: { span: { start: number; end: number }; pipelines: unknown[] }; let error: unknown; let declarations: unknown[]; let help: string; let serialized: string | undefined; beforeEach(() => { block = { span: { start: 1000, end: 1015 }, pipelines: [ { elements: [ { expr: { expr: { Call: { decl_id: 52, head: { start: 1000, end: 1007 }, arguments: [], }, }, span: { start: 1000, end: 1015 }, }, }, ], }, ], }; error = { UnknownFlag: ["version", "bogus", flagSpan, "help"] }; declarations = [{ decl_id: 52, name: "version", type: "built-in" }]; help = "Usage:\n > version {flags}\n"; serialized = undefined; execute.mockImplementation( async (_binary: string, args: string[], options: ExecFileOptions) => { if (options.signal?.aborted) throw new Error("aborted"); return { stdout: args.at(-1) === "help $env.PI_NU_HELP_TARGET" ? help : (serialized ?? JSON.stringify({ block: JSON.stringify(block), error: JSON.stringify(error), commands: declarations, })), }; }, ); }); afterEach(() => { vi.clearAllMocks(); }); function requestedHelp(): boolean { return execute.mock.calls.some( ([, args]) => args.at(-1) === "help $env.PI_NU_HELP_TARGET", ); } describe("Nu-native help analysis boundaries", () => { it.each(["not-json", "{}", '{"block":"not-json","error":"{}"}'])( "ignores malformed analysis: %s", async (data) => { serialized = data; await expect( diagnosticHelp("nu", source, process.cwd()), ).resolves.toBeUndefined(); expect(requestedHelp()).toBe(false); }, ); it.each([ { UnknownFlag: ["version", "bogus", { start: -1, end: 1015 }] }, { UnknownFlag: ["version", "bogus", { start: 1008, end: 5000 }] }, { UnknownFlag: ["version", "bogus", { start: 10, end: 17 }] }, { ExtraPositional: ["version", { start: 10, end: 17 }] }, { CantConvert: ["int", "string", flagSpan] }, { UnknownFlag: ["other command", "bogus", flagSpan] }, null, ])( "does not attach help for unrelated or invalid errors: %j", async (data) => { error = data; await expect( diagnosticHelp("nu", source, process.cwd()), ).resolves.toBeUndefined(); expect(requestedHelp()).toBe(false); }, ); it("rejects source/AST size mismatches and ambiguous owning calls", async () => { block.span.end++; await expect( diagnosticHelp("nu", source, process.cwd()), ).resolves.toBeUndefined(); block.span.end--; block.pipelines.push(block.pipelines[0]); await expect( diagnosticHelp("nu", source, process.cwd()), ).resolves.toBeUndefined(); expect(requestedHelp()).toBe(false); }); it("does not describe a local shadowing declaration using built-in help", async () => { declarations = [{ decl_id: 1, name: "version", type: "built-in" }]; await expect( diagnosticHelp("nu", source, process.cwd()), ).resolves.toBeUndefined(); expect(requestedHelp()).toBe(false); }); it("bounds help without ANSI while preserving command identity", async () => { help = `\x1b[31m${"🙂 documentation\n".repeat(2000)}\x1b[0m`; const result = await diagnosticHelp("nu", source, process.cwd()); expect(result).toMatchObject({ command: "version", truncated: true }); expect(Buffer.byteLength(result?.text ?? "")).toBeLessThanOrEqual(8192); expect(result?.text).not.toContain("\x1b"); }); it("passes source as data, never executable code", async () => { await diagnosticHelp("nu", source, process.cwd()); expect(execute.mock.calls[0]?.[1]).not.toContain(source); expect(execute.mock.calls[0]?.[2].env).toMatchObject({ PI_NU_HELP_SOURCE: source, }); }); it("quietly preserves failures when native analysis fails", async () => { execute.mockRejectedValue(new Error("output limit / executable failure")); await expect( diagnosticHelp("nu", source, process.cwd()), ).resolves.toBeUndefined(); }); it("cancels after native analysis without starting a help lookup", async () => { const controller = new AbortController(); const normal = execute.getMockImplementation()!; execute.mockImplementation( async (binary: string, args: string[], options: ExecFileOptions) => { const result = await normal(binary, args, options); controller.abort(); return result; }, ); await expect( diagnosticHelp("nu", source, process.cwd(), controller.signal), ).resolves.toBeUndefined(); }); it("uses one deadline for native analysis and help", async () => { execute.mockImplementation( (_binary: string, _args: string[], options: ExecFileOptions) => new Promise((_resolve, reject) => { options.signal?.addEventListener( "abort", () => reject(new Error("aborted")), { once: true }, ); }), ); await expect( diagnosticHelp("nu", source, process.cwd(), undefined, 10), ).resolves.toBeUndefined(); }); });