import { describe, expect, it } from "vitest"; import { readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { blockActive, composeNotebook, findStep, groupInputs, parseNotebook, renderStep } from "../src/index"; import type { Block, Notebook } from "../src/index"; const fence = "```"; const source = `--- title: Groups params: host: { type: host, required: true } user: { type: name, default: admin } port: { type: string } note: { type: string } mode: { type: choice, options: [a, b] } --- # Groups :::group{title="Connect to {{host}}"} First pick the server: ::param{name=host} ${fence}sh {check host="{{host}}" id=ping} id {{user}} ${fence} :::group{title="Optional details" collapsed} ::param{name=note} ::: ::: :::group{title="Prose only"} Nothing to fill in here. ::: `; const groups = (blocks: Block[]): Extract[] => blocks.flatMap(b => (b.type === "group" ? [b, ...groups(b.blocks)] : "blocks" in b ? groups(b.blocks) : [])); const hosts = ["web"]; describe("group and param directives", () => { it("parses nested groups, the collapsed flag and parameter fields", () => { const n = parseNotebook(source); expect(n.diagnostics).toEqual([]); const [connect, details, prose] = groups(n.blocks); expect(connect).toMatchObject({ title: "Connect to {{host}}", collapsed: false, range: { startLine: 13 } }); expect(connect!.blocks.map(b => b.type)).toEqual(["markdown", "param", "markdown", "step", "markdown", "group"]); expect(connect!.blocks[1]).toMatchObject({ type: "param", name: "host", range: { startLine: 16, endLine: 16 } }); expect(details).toMatchObject({ title: "Optional details", collapsed: true }); expect(details!.blocks).toEqual([expect.objectContaining({ type: "param", name: "note" })]); expect(prose!.blocks).toEqual([expect.objectContaining({ type: "markdown" })]); }); it("does not gate steps inside groups", () => { const n = parseNotebook(source); expect(findStep(n.blocks, "ping")?.attrs.host).toBe("{{host}}"); expect(blockActive(n, "ping", {})).toBe(true); expect(renderStep(n, findStep(n.blocks, "ping")!, { host: "web" }, {}, hosts).script).toBe("id admin\n"); }); it.each([ [":::group{}\n:::", 'group requires title="…"'], [':::group{title="x" open}\n:::', "Unknown group attribute: open"], [':::group{title="x" collapsed=yes}\n:::', "collapsed must be a flag"], [':::group{title="x"}\ntext', "Unclosed group container"], ["::param{name=nope}", "param references unknown parameter: nope"], ["::param{}", "param requires name=parameter"], ["::param{name=user label=x}", "Unknown param attribute: label"], ["::param name=user", "Malformed or unexpected directive"], ])("reports %j", (body, message) => { const n = parseNotebook(`---\nparams:\n user: { type: name }\n---\n${body}\n`); expect(n.diagnostics).toContainEqual(expect.objectContaining({ severity: "error", message, line: 5 })); }); it("namespaces fields and group titles of included notebooks", () => { const child = `---\ntitle: Child\nparams:\n name: { type: name, required: true }\n---\n:::group{title="Name {{name}}"}\n::param{name=name}\n:::\n`; const root = `::use{notebook="lib/child.md" as=c}\n`; const composed = composeNotebook("root.md", parseNotebook(root), path => (path === "lib/child.md" ? parseNotebook(child) : undefined)); expect(composed.diagnostics).toEqual([]); const [group] = groups(composed.blocks); expect(group).toMatchObject({ title: "Name {{c.name}}", blocks: [{ type: "param", name: "c.name" }] }); }); }); describe("groupInputs", () => { const notebook = parseNotebook(source); const [connect, details, prose] = groups(notebook.blocks); const status = (block: Block, values: Record, n: Notebook = notebook) => groupInputs(n, block, values, hosts); it("is missing while a required field is empty, filled when every input has a value", () => { expect(status(connect!, {})).toEqual({ status: "missing", params: ["host", "user", "note"], missing: ["host"], invalid: [] }); // user has a default; the optional note in the nested group still counts for the outer one. expect(status(connect!, { host: "web" }).status).toBe("optional"); expect(status(connect!, { host: "web", note: "x" })).toMatchObject({ status: "filled", missing: [] }); }); it("treats a parameter a step references as needed and reports invalid values", () => { expect(status(connect!, { host: "web", user: "" }).status).toBe("optional"); // default fills it const n = parseNotebook(source.replace("user: { type: name, default: admin }", "user: { type: name }")); const [group] = groups(n.blocks); expect(status(group!, { host: "web" }, n)).toMatchObject({ status: "missing", missing: ["user"] }); expect(status(group!, { host: "nope", user: "root" }, n)).toMatchObject({ status: "missing", missing: [], invalid: ["host"] }); }); it("is optional with only optional fields and none without inputs", () => { expect(status(details!, {})).toEqual({ status: "optional", params: ["note"], missing: [], invalid: [] }); expect(status(details!, { note: "x" }).status).toBe("filled"); expect(status(prose!, {})).toEqual({ status: "none", params: [], missing: [], invalid: [] }); }); it("ignores inactive when sections and runtime values", () => { const n = parseNotebook(`--- params: mode: { type: choice, options: [a, b], default: a } x: { type: string, required: true } --- :::group{title="G"} :::when{mode=b} ::param{name=x} ::: ${fence}sh {run on=local id=r capture=out} echo {{mode}} ${fence} ${fence}sh {run on=local id=s} echo {{out}} ${fence} ::: `); expect(n.diagnostics).toEqual([]); const [group] = groups(n.blocks); expect(status(group!, {}, n)).toEqual({ status: "filled", params: ["mode"], missing: [], invalid: [] }); expect(status(group!, { mode: "b" }, n)).toMatchObject({ status: "missing", missing: ["x"] }); }); it("counts an included notebook's own parameters for its ::use section", () => { const child = `---\ntitle: Child\nparams:\n name: { type: name, required: true }\n size: { type: string }\n---\ntext\n`; const composed = composeNotebook("root.md", parseNotebook(`::use{notebook="lib/child.md" as=c}\n`), () => parseNotebook(child)); const use = composed.blocks.find(b => b.type === "use")!; expect(status(use, {}, composed)).toEqual({ status: "missing", params: ["c.name", "c.size"], missing: ["c.name"], invalid: [] }); expect(status(use, { "c.name": "x" }, composed).status).toBe("optional"); }); }); describe("shipped templates", () => { const root = fileURLToPath(new URL("../../../templates/workspace/notebooks/", import.meta.url)); const files = readdirSync(root, { recursive: true, encoding: "utf8" }).filter(f => f.endsWith(".md")); it.each(files)("%s parses without errors", file => { const n = parseNotebook(readFileSync(join(root, file), "utf8")); // Included notebooks are resolved by the server; parsing alone must be clean. expect(n.diagnostics).toEqual([]); }); it("guides the admin-user example with fields in each group", () => { const n = parseNotebook(readFileSync(join(root, "admin-user.md"), "utf8")); const all = groups(n.blocks); expect(all.map(g => g.title)).toEqual(["1. Pick the server", "2. Describe the user", "3. Create the user", "4. Verify"]); expect(groupInputs(n, all[2]!, {}, hosts)).toMatchObject({ status: "missing", missing: ["host", "user", "pubkey"] }); const values = { host: "web", user: "ops", pubkey: "ssh-ed25519 AAAA ops" }; expect(all.map(g => groupInputs(n, g, values, hosts).status)).toEqual(["filled", "filled", "filled", "filled"]); expect(renderStep(n, findStep(n.blocks, "create")!, values, {}, hosts).script) .toContain(String.raw`printf '%s\n' 'ssh-ed25519 AAAA ops' > /home/ops/.ssh/authorized_keys`); }); }); describe("step gating for guided notebooks", () => { const n = parseNotebook(`--- params: host: { type: host, required: true } user: { type: name, required: true } TOKEN: { type: secret, required: true } OTHER: { type: secret, required: true } --- ${fence}sh {check host="{{host}}" id=first} true ${fence} ${fence}sh {run host="{{host}}" id=later} useradd {{user}} ${fence} ${fence}sh {run host="{{host}}" id=token} curl -H "Authorization: Bearer \${TOKEN}" https://example.invalid ${fence} `); const step = (id: string) => findStep(n.blocks, id)!; const render = (id: string, values: Record) => renderStep(n, step(id), values, {}, hosts); it("blocks a step only on the values it uses", () => { // Required, but unused by this step: an earlier step runs before later values are known. expect(render("first", { host: "web" })).toMatchObject({ missing: [], invalid: {} }); expect(render("later", { host: "web" }).missing).toEqual(["user"]); }); it("treats a required secret the script reads as $NAME or \${NAME} as used", () => { expect(render("token", { host: "web" }).missing).toEqual(["TOKEN"]); expect(render("token", { host: "web", TOKEN: "t" })).toMatchObject({ missing: [], invalid: {} }); // A $TOKENX or OTHER mention is not TOKEN. expect(render("first", { host: "web" }).missing).not.toContain("OTHER"); }); });