Files
ShellBook/packages/core/src/parser.ts
T
Florian Schmidt 845d6c828e feat: chained notebooks with when sections and host blocks (#11)
A notebook can include another one and continue with what it produced:

- core: parse :::when{param=a,b}, ::use{notebook= as= with=} and
  ::host{name= address= user= port= capture=}; composeNotebook namespaces
  an included notebook's params, steps, captures and templates by alias
  (cycles, missing files, depth > 4 and child errors are reported on the
  use line). Defaults may reference captures and builtins
  ({{shellbook.public_key}}); required params and secrets gate only steps
  of their own scope; secretEnv passes a scope's secrets under local names.
- protocol: NotebookResponse gains includes and builtins.
- server: compose includes on load, inject builtins (client values are
  ignored), refuse steps in inactive when sections.
- web: render when/use/host blocks, group included params in the form,
  add a created machine to Hosts and capture its name, reload when an
  included notebook changes, run all checks only for active steps,
  authoring snippets for when, use and host.
2026-11-16 11:42:12 +01:00

269 lines
15 KiB
TypeScript

import { parseDocument } from "yaml";
import type { Block, Notebook, ParamDef, Step, StepAttrs } from "./types";
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
const paramTypes = new Set(["host", "name", "path", "string", "choice", "secret"]);
const identifier = /^[A-Za-z_][A-Za-z0-9_]*$/;
/** Workspace notebook path relative to notebooks/: forward slashes, no `..`, Markdown only. */
export const includePath = (value: string) =>
/^[^\\\0\r\n:]+\.md$/.test(value) && value.split("/").every(part => part && part !== "." && part !== "..");
/** Small attribute scanner: quoted values may contain whitespace, braces and escaped quotes. */
function attributes(text: string, error: (message: string) => void): Map<string, (string | true)[]> {
const result = new Map<string, (string | true)[]>();
let rest = text.trim();
while (rest) {
const key = /^[A-Za-z_][\w-]*/.exec(rest)?.[0];
if (!key) { error(`Malformed attributes: ${rest}`); break; }
rest = rest.slice(key.length);
let value: string | true = true;
if (rest.startsWith("=")) {
rest = rest.slice(1);
const quote = rest[0];
if (quote === '"' || quote === "'") {
rest = rest.slice(1);
value = "";
let closed = false;
while (rest) {
const c = rest[0]!;
rest = rest.slice(1);
if (c === quote) { closed = true; break; }
if (c === "\\" && (rest[0] === quote || rest[0] === "\\")) {
value += rest[0]; rest = rest.slice(1);
} else value += c;
}
if (!closed) error(`Unclosed quote for ${key}`);
} else {
value = /^\S*/.exec(rest)![0];
rest = rest.slice(value.length);
if (!value) error(`Missing value for ${key}`);
}
}
if (rest && !/^\s/.test(rest)) { error(`Expected whitespace after ${key}`); break; }
result.set(key, [...(result.get(key) ?? []), value]);
rest = rest.trimStart();
}
return result;
}
export function parseNotebook(source: string): Notebook {
const notebook: Notebook = { title: "Untitled", params: [], blocks: [], diagnostics: [] };
const rawLines = source.split("\n");
const lines = rawLines.map(line => line.replace(/\r$/, ""));
let hasTitle = false;
// A trailing newline terminates the preceding line; it does not create a source line.
if (lines.at(-1) === "") lines.pop();
const error = (message: string, line?: number) => notebook.diagnostics.push({ severity: "error", message, line });
let start = 0;
if (lines[0]?.replace(/^\uFEFF/, "") === "---") {
const end = lines.findIndex((line, i) => i > 0 && /^(---|\.\.\.)\s*$/.test(line));
if (end < 0) error("Unclosed frontmatter", 1);
else {
start = end + 1;
try {
const doc = parseDocument(lines.slice(1, end).join("\n"));
for (const e of doc.errors) error(`Invalid YAML: ${e.message}`, (e.linePos?.[0]?.line ?? 1) + 1);
const data: unknown = doc.toJS({ maxAliasCount: 100 });
if (!record(data)) error("Frontmatter must be a mapping", 1);
else {
if (typeof data.title === "string" && data.title.trim()) { notebook.title = data.title; hasTitle = true; }
else if (data.title !== undefined) error("title must be a non-empty string", 2);
if (data.params !== undefined && !record(data.params)) error("params must be a mapping", 2);
if (record(data.params)) for (const [name, raw] of Object.entries(data.params)) {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) error(`Invalid parameter name: ${name}`, 2);
if (!record(raw)) { error(`Parameter ${name} must be a mapping`, 2); continue; }
if (!paramTypes.has(String(raw.type))) { error(`Unknown param type for ${name}`, 2); continue; }
const def: ParamDef = { name, type: raw.type as ParamDef["type"], required: raw.required === true };
for (const key of Object.keys(raw)) if (!["type", "required", "default", "label", "options"].includes(key)) error(`Unknown parameter field ${key} for ${name}`, 2);
if (raw.required !== undefined && typeof raw.required !== "boolean") error(`required must be boolean for ${name}`, 2);
if (raw.default !== undefined) {
if (def.type === "secret") error(`Secret ${name} cannot have a default`, 2);
else if (typeof raw.default === "string" || typeof raw.default === "number" || typeof raw.default === "boolean") def.default = String(raw.default);
else error(`Invalid default for ${name}`, 2);
}
if (typeof raw.label === "string") def.label = raw.label;
else if (raw.label !== undefined) error(`Invalid label for ${name}`, 2);
if (Array.isArray(raw.options) && raw.options.every(x => typeof x === "string")) def.options = raw.options;
else if (raw.options !== undefined) error(`Invalid options for ${name}`, 2);
if (def.type === "choice" && !def.options?.length) error(`Choice ${name} needs options`, 2);
notebook.params.push(def);
}
}
} catch { error("Invalid YAML frontmatter", 2); }
}
}
const ids = new Set<string>();
const afterRefs: { id: string; line: number }[] = [];
const aliases = new Set<string>();
let stepNumber = 0;
let hostNumber = 0;
let heading: string | undefined;
let i = start;
const parseBlocks = (nested: boolean, depth = 0): Block[] => {
const blocks: Block[] = [];
let markdownStart = i;
const flush = () => {
if (i > markdownStart) blocks.push({ type: "markdown", text: rawLines.slice(markdownStart, i).join("\n") + (i < lines.length || /\n$/.test(source) ? "\n" : ""), range: { startLine: markdownStart + 1, endLine: i } });
};
while (i < lines.length) {
const line = lines[i]!;
if (/^\s{0,3}:::\s*$/.test(line) && nested) { flush(); return blocks; }
const after = /^\s{0,3}:::after\{(.*)\}\s*$/.exec(line);
if (after && depth < 100) {
flush(); const begin = i++;
const attrs = attributes(after[1]!, m => error(m, begin + 1));
const ref = attrs.get("step")?.[0];
const id = typeof ref === "string" ? ref : "";
if (!id) error("after requires step=id", begin + 1);
for (const key of attrs.keys()) if (!["step", "failed"].includes(key)) error(`Unknown after attribute: ${key}`, begin + 1);
if (attrs.has("failed") && attrs.get("failed")![0] !== true) error("failed must be a flag", begin + 1);
afterRefs.push({ id, line: begin + 1 });
const children = parseBlocks(true, depth + 1);
if (i === lines.length) error("Unclosed after container", begin + 1);
else i++;
blocks.push({ type: "after", stepId: id, onFailure: attrs.has("failed"), blocks: children, range: { startLine: begin + 1, endLine: i } });
markdownStart = i; continue;
}
const when = /^\s{0,3}:::when\{(.*)\}\s*$/.exec(line);
if (when && depth < 100) {
flush(); const begin = i++;
const attrs = attributes(when[1]!, m => error(m, begin + 1));
const [param, raw] = [...attrs][0] ?? [];
const value = raw?.[0];
if (attrs.size !== 1 || typeof value !== "string") error("when requires exactly one param=value[,value]", begin + 1);
const values = typeof value === "string" ? value.split(",").map(v => v.trim()).filter(Boolean) : [];
const def = notebook.params.find(p => p.name === param);
if (param && !def) error(`when references unknown parameter: ${param}`, begin + 1);
else if (def?.type === "secret") error("when cannot test a secret", begin + 1);
else if (def?.options) for (const v of values) if (!def.options.includes(v)) error(`when value is not an option of ${param}: ${v}`, begin + 1);
const children = parseBlocks(true, depth + 1);
if (i === lines.length) error("Unclosed when container", begin + 1);
else i++;
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);
if (leaf) {
flush();
const lineNo = i + 1;
const attrs = attributes(leaf[2]!, m => error(m, lineNo));
const get = (key: string): string | undefined => {
const v = attrs.get(key);
if (v && (v.length > 1 || v[0] === true)) error(`${key} requires one value`, lineNo);
return typeof v?.[0] === "string" ? v[0] : undefined;
};
const range = { startLine: lineNo, endLine: lineNo };
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") ?? "";
if (!includePath(path)) error('use requires notebook="dir/name.md" (relative to notebooks/)', lineNo);
if (!identifier.test(alias) || alias === "shellbook") error("use requires as=alias (letters, digits, _; not shellbook)", lineNo);
else if (aliases.has(alias)) error(`Duplicate use alias: ${alias}`, lineNo);
aliases.add(alias);
const bindings = Object.create(null) as Record<string, string>;
for (const value of attrs.get("with") ?? []) {
if (value === true) { error("with requires name=value pairs", lineNo); continue; }
// Values may contain commas; a new binding starts only at ",name=".
for (const pair of value.split(/,(?=\s*[A-Za-z_][A-Za-z0-9_]*\s*=)/)) {
const eq = pair.indexOf("=");
const name = pair.slice(0, Math.max(eq, 0)).trim();
if (eq <= 0 || !identifier.test(name)) error("with requires name=value pairs", lineNo);
else if (Object.hasOwn(bindings, name)) error(`Duplicate with binding: ${name}`, lineNo);
else bindings[name] = pair.slice(eq + 1).trim();
}
}
blocks.push({ type: "use", scope: alias, path, bindings, blocks: [], range });
} else {
hostNumber++;
for (const key of attrs.keys()) if (!["id", "name", "address", "user", "port", "capture"].includes(key)) error(`Unknown host attribute: ${key}`, lineNo);
const id = get("id") || `host-${hostNumber}`;
if (ids.has(id)) error(`Duplicate step id: ${id}`, lineNo);
ids.add(id);
const name = get("name"), address = get("address");
if (!name || !address) error("host requires name and address", lineNo);
const capture = get("capture");
if (capture !== undefined && !identifier.test(capture)) error("Invalid capture name", lineNo);
blocks.push({ type: "host", id, name: name ?? "", address: address ?? "", user: get("user") ?? "root", port: get("port") ?? "22", capture, range });
}
i++; markdownStart = i; continue;
}
const fence = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
if (fence) {
const begin = i;
const marker = fence[1]!;
const info = fence[2]!.trim();
const match = /^(sh|bash)\s+\{(run|check)(?:\s+([\s\S]*))?\}$/.exec(info);
let end = i + 1;
const closing = new RegExp(`^ {0,3}${marker[0]}{${marker.length},}\\s*$`);
while (end < lines.length && !closing.test(lines[end]!)) end++;
if (!match) { i = end < lines.length ? end + 1 : end; continue; }
flush();
stepNumber++;
if (end === lines.length) error("Unclosed step fence", begin + 1);
const attrs = attributes(match[3] ?? "", m => error(m, begin + 1));
const get = (key: string): string | undefined => {
const v = attrs.get(key)?.[0];
if (v === true) error(`${key} requires a value`, begin + 1);
return typeof v === "string" ? v : undefined;
};
for (const [key, vals] of attrs) {
if (!["host", "on", "id", "title", "sudo", "confirm", "capture", "artifacts", "upload", "timeout"].includes(key)) error(`Unknown attribute: ${key}`, begin + 1);
if (vals.length > 1 && key !== "upload") error(`Duplicate attribute: ${key}`, begin + 1);
if (["sudo", "confirm"].includes(key) && vals[0] !== true) error(`${key} must be a flag`, begin + 1);
}
const kind = match[2] as Step["kind"];
const title = get("title");
const id = get("id") || title?.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || `step-${stepNumber}`;
if (ids.has(id)) error(`Duplicate step id: ${id}`, begin + 1);
ids.add(id);
const on = get("on");
if (on !== undefined && on !== "local") error("on must be local", begin + 1);
const host = get("host");
if (on && host) error("host and on cannot be combined", begin + 1);
const timeout = get("timeout");
const timeoutSec = timeout === undefined ? (kind === "run" ? 300 : 30) : Number(timeout);
if (!Number.isFinite(timeoutSec) || timeoutSec <= 0) error("timeout must be positive seconds", begin + 1);
const artifacts = get("artifacts")?.split(",").map(x => x.trim()) ?? [];
const uploads: StepAttrs["uploads"] = [];
for (const value of attrs.get("upload") ?? []) {
if (value === true) { error("upload requires src:dst", begin + 1); continue; }
for (const pair of value.split(",")) {
const colon = pair.indexOf(":");
if (colon <= 0 || colon === pair.length - 1) error("upload requires src:dst", begin + 1);
else uploads.push({ src: pair.slice(0, colon).trim(), dst: pair.slice(colon + 1).trim() });
}
}
if (kind === "check" && (attrs.has("artifacts") || attrs.has("upload"))) error("Checks cannot declare artifacts or uploads", begin + 1);
const capture = get("capture");
if (capture && !identifier.test(capture)) error("Invalid capture name", begin + 1);
const step: Step = {
kind,
lang: match[1]!,
attrs: {
id, title, host: on === "local" ? undefined : host,
local: on === "local", sudo: attrs.has("sudo"),
confirm: kind === "run" && attrs.has("confirm"), capture,
artifacts: kind === "run" ? artifacts : [],
uploads: kind === "run" ? uploads : [], timeoutSec,
},
// LF-normalized: bash must never see a trailing \r from CRLF notebooks.
script: lines.slice(begin + 1, end).join("\n")
+ (end > begin + 1 && (end < lines.length || /\n$/.test(source)) ? "\n" : ""),
range: { startLine: begin + 1, endLine: end < lines.length ? end + 1 : end },
};
blocks.push({ type: "step", step });
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);
i++;
}
flush(); return blocks;
};
notebook.blocks = parseBlocks(false);
if (!hasTitle && heading) notebook.title = heading;
for (const ref of afterRefs) if (!ids.has(ref.id)) error(`after references unknown step: ${ref.id}`, ref.line);
return notebook;
}