feat(core): parameter fields in text, groups and gating by used values (#16)

- `::param{name=x}` places a parameter's input inside the text.
- `:::group{title="…" collapsed}` is a collapsible container for anything;
  groups are presentational and never gate steps. Included notebooks
  namespace field names and group titles.
- `groupInputs` reports a container's input status (missing, filled,
  optional, none) from its fields, the parameters its steps use and, for
  `::use`, the included notebook's parameters.
- A step is gated only by the values it uses: referenced parameters, the
  required secrets its script reads and valid set secrets of its scope.
  Unused required parameters no longer block early steps of a guided
  runbook.
- Spec §3.2/§3.6/§3.7, workspace format guide and a guided admin-user
  example notebook.
This commit is contained in:
Florian Schmidt
2026-11-16 16:49:47 +01:00
parent cae72c7f28
commit bdbcd2dcd5
10 changed files with 475 additions and 31 deletions
+10 -8
View File
@@ -15,7 +15,7 @@ export function notebookIncludes(notebook: Notebook): string[] {
const walk = (blocks: Block[]) => {
for (const block of blocks) {
if (block.type === "use" && !block.blocks.length) { if (includePath(block.path)) paths.push(block.path); }
else if (block.type === "after" || block.type === "when" || block.type === "use") walk(block.blocks);
else if (block.type === "after" || block.type === "when" || block.type === "use" || block.type === "group") walk(block.blocks);
}
};
walk(notebook.blocks);
@@ -53,6 +53,8 @@ function prefixBlocks(blocks: Block[], alias: string): Block[] {
case "after": return { ...block, stepId: qualify(alias, block.stepId), blocks: prefixBlocks(block.blocks, alias) };
case "when": return { ...block, param: qualify(alias, block.param), blocks: prefixBlocks(block.blocks, alias) };
case "use": return { ...block, scope: qualify(alias, block.scope), bindings: {}, blocks: prefixBlocks(block.blocks, alias) };
case "group": return { ...block, title: rewrite(block.title, alias), blocks: prefixBlocks(block.blocks, alias) };
case "param": return { ...block, name: qualify(alias, block.name) };
case "host": return {
...block, id: qualify(alias, block.id), scope: scoped(alias, block.scope),
name: rewrite(block.name, alias), address: rewrite(block.address, alias),
@@ -77,7 +79,7 @@ function blockIds(blocks: Block[], into: string[] = []): string[] {
for (const block of blocks) {
if (block.type === "step") into.push(block.step.attrs.id);
else if (block.type === "host") into.push(block.id);
else if (block.type !== "markdown") blockIds(block.blocks, into);
else if ("blocks" in block) blockIds(block.blocks, into);
}
return into;
}
@@ -98,7 +100,7 @@ function compose(path: string, notebook: Notebook, load: (path: string) => Noteb
const params: ParamDef[] = [...notebook.params];
const fail = (message: string, line: number) => diagnostics.push({ severity: "error", message, line });
const resolve = (blocks: Block[]): Block[] => blocks.map((block): Block => {
if (block.type === "after" || block.type === "when") return { ...block, blocks: resolve(block.blocks) };
if (block.type === "after" || block.type === "when" || block.type === "group") return { ...block, blocks: resolve(block.blocks) };
if (block.type !== "use") return block;
const line = block.range.startLine;
// The parser already reported an invalid path; never hand it to the loader.
@@ -132,11 +134,11 @@ function compose(path: string, notebook: Notebook, load: (path: string) => Noteb
return { ...notebook, params, blocks, diagnostics };
}
/** Find a step anywhere in the block tree (after, when and use containers). */
/** Find a step anywhere in the block tree (after, when, use and group containers). */
export function findStep(blocks: Block[], id: string): Step | undefined {
for (const block of blocks) {
if (block.type === "step" && block.step.attrs.id === id) return block.step;
if (block.type === "after" || block.type === "when" || block.type === "use") {
if ("blocks" in block) {
const found = findStep(block.blocks, id);
if (found) return found;
}
@@ -155,7 +157,7 @@ export function blockActive(notebook: Notebook, id: string, values: ParamValues)
if (block.type === "when") {
const found = walk(block.blocks, active && block.values.includes(values[block.param] ?? ""));
if (found !== undefined) return found;
} else if (block.type === "after" || block.type === "use") {
} else if (block.type === "after" || block.type === "use" || block.type === "group") {
const found = walk(block.blocks, active);
if (found !== undefined) return found;
}
@@ -171,7 +173,7 @@ export function scopeActive(notebook: Notebook, scope: string, values: ParamValu
const walk = (blocks: Block[], active: boolean): boolean | undefined => {
for (const block of blocks) {
if (block.type === "use" && block.scope === scope) return active;
if (block.type === "markdown" || block.type === "step" || block.type === "host") continue;
if (!("blocks" in block)) continue;
const found = walk(block.blocks, active && (block.type !== "when" || block.values.includes(values[block.param] ?? "")));
if (found !== undefined) return found;
}
@@ -185,7 +187,7 @@ export function captureNames(blocks: Block[], into = new Set<string>()): Set<str
for (const block of blocks) {
if (block.type === "step" && block.step.attrs.capture) into.add(block.step.attrs.capture);
else if (block.type === "host" && block.capture) into.add(block.capture);
else if (block.type !== "markdown" && block.type !== "step" && block.type !== "host") captureNames(block.blocks, into);
else if ("blocks" in block) captureNames(block.blocks, into);
}
return into;
}
+77 -11
View File
@@ -1,5 +1,5 @@
// Public API of @shellbook/core. Pure functions, no I/O.
import type { Block, Notebook, ParamValues, RenderedHost, RenderedStep, Step } from "./types";
import type { Block, GroupInputs, Notebook, ParamValues, RenderedHost, RenderedStep, Step } from "./types";
import { captureNames, isBuiltin } from "./compose";
export type * from "./types";
export type * from "./protocol";
@@ -78,8 +78,10 @@ export function resolveParams(
}
/**
* Shared template substitution for steps and host blocks. Required params gate only
* blocks of their own scope: an included notebook's form does not block the parent.
* Shared template substitution for steps and host blocks. A block needs exactly the values
* it uses (spec §3.6): referenced parameters and runtime values, and for scripts the
* required secrets of its scope that the script reads. Required parameters it does not
* use never block it, so guided notebooks can run early steps before later values exist.
*/
function substitution(notebook: Notebook, scope: string | undefined, values: ParamValues, runtime: ParamValues, hostNames: readonly string[]) {
const resolved = resolveParams(notebook, values, hostNames, runtime);
@@ -87,12 +89,18 @@ function substitution(notebook: Notebook, scope: string | undefined, values: Par
const defs = new Map(notebook.params.map(def => [def.name, def]));
const invalid = dictionary();
const missing = new Set<string>();
for (const def of notebook.params) {
if ((def.scope ?? "") !== (scope ?? "")) continue;
if (def.required && !resolved.values[def.name]) missing.add(def.name);
if ((def.required || def.type === "secret") && resolved.values[def.name]
&& own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!;
}
const ownSecrets = notebook.params.filter(def => def.type === "secret" && (def.scope ?? "") === (scope ?? ""));
// Every set secret of the scope is passed as an env var (secretEnv), so it must be valid.
for (const def of ownSecrets)
if (resolved.values[def.name] && own(resolved.errors, def.name)) invalid[def.name] = resolved.errors[def.name]!;
/** A required secret the script reads as $NAME or ${NAME} (its local name) must be set. */
const readsSecrets = (script: string) => {
for (const def of ownSecrets) {
const local = def.scope ? def.name.slice(def.scope.length + 1) : def.name;
if (def.required && !resolved.values[def.name] && new RegExp("\\$\\{?" + local + "(?![A-Za-z0-9_])").test(script))
missing.add(def.name);
}
};
const substitute = (text: string, script: boolean): string => text.replace(template, (match, name: string) => {
const def = defs.get(name);
if (def?.type === "secret") { invalid[name] = "Secrets must be referenced as environment variables"; return match; }
@@ -110,7 +118,7 @@ function substitution(notebook: Notebook, scope: string | undefined, values: Par
if (own(invalid, name)) return match;
return script ? shellQuote(value) : value;
});
return { substitute, invalid, missing };
return { substitute, readsSecrets, invalid, missing };
}
/**
@@ -124,8 +132,9 @@ export function renderStep(
runtime: ParamValues,
hostNames: readonly string[],
): RenderedStep {
const { substitute, invalid, missing } = substitution(notebook, step.attrs.scope, values, runtime, hostNames);
const { substitute, readsSecrets, invalid, missing } = substitution(notebook, step.attrs.scope, values, runtime, hostNames);
const script = substitute(step.script, true);
readsSecrets(step.script);
const host = step.attrs.local || step.attrs.host === undefined ? undefined : substitute(step.attrs.host, false);
if (!step.attrs.local && (!host || !hostNames.includes(host))) invalid.host ??= "Unknown or missing target host";
const plainFile = (name: string) => !!name && !/[\\/\0\r\n]/.test(name) && !name.includes("..");
@@ -162,6 +171,63 @@ export function renderHost(
return { id: block.id, name, address, user, port, missing: [...missing], invalid };
}
/**
* Input status of a container block (`:::group`, `::use`; spec §3.7). Its inputs are its
* `::param` fields, the parameters its steps and host blocks reference (those are needed:
* the step cannot run without them) and, for `::use`, the included notebook's parameters.
* Sections of inactive `:::when` blocks are ignored; runtime values are not inputs.
*/
export function groupInputs(
notebook: Notebook,
block: Block,
values: ParamValues,
hostNames: readonly string[],
runtime: ParamValues = {},
): GroupInputs {
const resolved = resolveParams(notebook, values, hostNames, runtime);
const defs = new Map(notebook.params.map(def => [def.name, def]));
const params: string[] = [];
const needed = new Set<string>();
const add = (name: string, need: boolean) => {
const def = defs.get(name);
if (!def) return;
if (!params.includes(name)) params.push(name);
if (need || def.required) needed.add(name);
};
const references = (text: string) => { for (const match of text.matchAll(template)) add(match[1]!, true); };
const walk = (items: Block[]) => {
for (const item of items) {
switch (item.type) {
case "param": add(item.name, false); break;
case "step": {
const attrs = item.step.attrs;
// In display order: the target first, then the script.
if (attrs.host !== undefined) references(attrs.host);
references(item.step.script);
attrs.artifacts.forEach(references);
for (const upload of attrs.uploads) { references(upload.src); references(upload.dst); }
break;
}
case "host": [item.name, item.address, item.user, item.port].forEach(references); break;
case "when": if (item.values.includes(resolved.values[item.param] ?? "")) walk(item.blocks); break;
case "use":
for (const def of notebook.params) if (def.scope === item.scope) add(def.name, false);
walk(item.blocks); break;
case "after": case "group": walk(item.blocks); break;
case "markdown": break;
}
}
};
walk([block]);
const filled = (name: string) => !!resolved.values[name];
const missing = params.filter(name => needed.has(name) && !filled(name));
const invalid = params.filter(name => filled(name) && own(resolved.errors, name));
const status = missing.length || invalid.length ? "missing"
: !params.length ? "none"
: params.every(filled) ? "filled" : "optional";
return { status, params, missing, invalid };
}
/** Substitute prose without quoting; secrets always appear masked. */
export function renderText(text: string, values: ParamValues, notebook: Notebook): string {
const secrets = new Set(notebook.params.filter(def => def.type === "secret").map(def => def.name));
+26 -3
View File
@@ -156,7 +156,24 @@ export function parseNotebook(source: string): Notebook {
blocks.push({ type: "when", param: param ?? "", values, blocks: children, range: { startLine: begin + 1, endLine: i } });
markdownStart = i; continue;
}
const leaf = /^\s{0,3}::(use|host)\{(.*)\}\s*$/.exec(line);
const group = /^\s{0,3}:::group\{(.*)\}\s*$/.exec(line);
if (group && depth < 100) {
flush(); const begin = i++;
const attrs = attributes(group[1]!, m => error(m, begin + 1));
for (const key of attrs.keys()) if (!["title", "collapsed"].includes(key)) error(`Unknown group attribute: ${key}`, begin + 1);
const title = attrs.get("title");
if (title?.length !== 1 || typeof title[0] !== "string" || !title[0].trim()) error('group requires title="…"', begin + 1);
if (attrs.has("collapsed") && attrs.get("collapsed")![0] !== true) error("collapsed must be a flag", begin + 1);
const children = parseBlocks(true, depth + 1);
if (i === lines.length) error("Unclosed group container", begin + 1);
else i++;
blocks.push({
type: "group", title: typeof title?.[0] === "string" ? title[0] : "", collapsed: attrs.has("collapsed"),
blocks: children, range: { startLine: begin + 1, endLine: i },
});
markdownStart = i; continue;
}
const leaf = /^\s{0,3}::(use|host|param)\{(.*)\}\s*$/.exec(line);
if (leaf) {
flush();
const lineNo = i + 1;
@@ -167,7 +184,13 @@ export function parseNotebook(source: string): Notebook {
return typeof v?.[0] === "string" ? v[0] : undefined;
};
const range = { startLine: lineNo, endLine: lineNo };
if (leaf[1] === "use") {
if (leaf[1] === "param") {
for (const key of attrs.keys()) if (key !== "name") error(`Unknown param attribute: ${key}`, lineNo);
const name = get("name") ?? "";
if (!name) error("param requires name=parameter", lineNo);
else if (!notebook.params.some(def => def.name === name)) error(`param references unknown parameter: ${name}`, lineNo);
blocks.push({ type: "param", name, range });
} else if (leaf[1] === "use") {
for (const key of attrs.keys()) if (!["notebook", "as", "with"].includes(key)) error(`Unknown use attribute: ${key}`, lineNo);
const path = get("notebook") ?? "";
const alias = get("as") ?? "";
@@ -270,7 +293,7 @@ export function parseNotebook(source: string): Notebook {
i = end < lines.length ? end + 1 : end; markdownStart = i; continue;
}
heading ??= /^ {0,3}#\s+(.+?)\s*#*\s*$/.exec(line)?.[1];
if (/^\s*:::/.test(line) || /^\s{0,3}::(use|host)\b/.test(line)) error("Malformed or unexpected directive", i + 1);
if (/^\s*:::/.test(line) || /^\s{0,3}::(use|host|param)\b/.test(line)) error("Malformed or unexpected directive", i + 1);
i++;
}
flush(); return blocks;
+37
View File
@@ -105,6 +105,26 @@ export type Block =
blocks: Block[];
range: SourceRange;
}
| {
/** `::param{name=x}` — the parameter's input field at this point of the text. */
type: "param";
/** Parameter name (namespaced like `ct.hostname` inside an included notebook). */
name: string;
range: SourceRange;
}
| {
/**
* `:::group{title="…" collapsed}` — a titled, collapsible container for any blocks.
* Purely presentational: it never gates display or execution.
*/
type: "group";
/** Template; `{{name}}` is substituted like prose. */
title: string;
/** `collapsed` flag: starts closed until the user opens it. */
collapsed: boolean;
blocks: Block[];
range: SourceRange;
}
| {
/** `::host{name= address= user= port= capture=}` — add a machine to Hosts from the notebook. */
type: "host";
@@ -120,6 +140,23 @@ export type Block =
range: SourceRange;
};
/**
* How far the inputs of a group (or included notebook) are filled in:
* "missing" — a needed value is empty or a value is invalid; "filled" — every input has a
* value; "optional" — only optional inputs are empty; "none" — the group has no inputs.
*/
export type InputStatus = "none" | "optional" | "filled" | "missing";
export interface GroupInputs {
status: InputStatus;
/** Parameters the group asks for or uses, in document order. */
params: string[];
/** Needed (required, or referenced by a step or host block) but empty. */
missing: string[];
/** Filled but invalid. */
invalid: string[];
}
/** A `::host` block with all templates resolved. */
export interface RenderedHost {
id: string;
+1 -1
View File
@@ -46,7 +46,7 @@ const files: Record<string, string> = { "infra/lxc.md": lxc, "services/web.md":
const load = (path: string) => files[path] === undefined ? undefined : parseNotebook(files[path]!);
const composed = () => composeNotebook("services/web.md", parseNotebook(service), load);
function all(blocks: Block[]): Block[] {
return blocks.flatMap(b => b.type === "markdown" || b.type === "step" || b.type === "host" ? [b] : [b, ...all(b.blocks)]);
return blocks.flatMap(b => "blocks" in b ? [b, ...all(b.blocks)] : [b]);
}
const hosts = ["pve", "web-ct", "existing"];
+2 -1
View File
@@ -132,7 +132,8 @@ describe("rendering and secrets", () => {
it("blocks missing and invalid used params, unknown variables and invalid hosts", () => {
const n = book(" x: {type: name}\n required: {type: string, required: true}\n unused: {type: name}", "{{x}} {{unknown}} {{empty}}", "host=missing");
const r = render(n, { x: "bad value", unused: "bad value" }, { empty: "" });
expect(r.missing).toEqual(["required", "empty"]);
// An unused required param does not block the step (guided notebooks, spec §3.6).
expect(r.missing).toEqual(["empty"]);
expect(Object.keys(r.invalid).sort()).toEqual(["host", "unknown", "x"]);
expect(r.script).toBe("{{x}} {{unknown}} {{empty}}\n");
});
+202
View File
@@ -0,0 +1,202 @@
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<Block, { type: "group" }>[] =>
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<string, string>, 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<string, string>) => 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");
});
});